/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.code.p.narcissus.ui.components;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
 * Simple panel displaying an image
 * @author jadoj
 */
public class ImagePanel extends JPanel {

    private BufferedImage image;
    private int scale = 0;

    public ImagePanel() {
        addMouseWheelListener(new java.awt.event.MouseWheelListener() {

            @Override
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                scale(evt.getWheelRotation());
            }
        });
    }

    public void setImage(File imageLocation) throws IOException {
        this.image = ImageIO.read(imageLocation);
        this.repaint();
    }

    protected BufferedImage getImage() {
        return this.image;
    }

    protected int getScale() {
        return scale;
    }

    public void scale(int scale) {
        this.scale += scale;
        if (this.scale < -9) {
            this.scale = -9;
        } else if (this.scale > 30) {
            this.scale = 30;
        }

        repaint();
    }

    protected int getScalePercentage() {
        int scalePercentage = 100 + scale * 10;
        return scalePercentage < 10 ? 10 : scalePercentage > 400 ? 400 : scalePercentage;
    }

    public int getScaledValue(int originalValue) {
        return new Double(((double) originalValue) / 100 * getScalePercentage()).intValue();
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.GRAY);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());

        if (getImage() != null) {
            resizePanel();
            g.drawImage(getImage(), 0, 0, getScaledValue(getImage().getWidth()), getScaledValue(getImage().getHeight()), this);
        }
    }

    protected void resizePanel(){
        if(getImage() != null){
            this.setPreferredSize(new Dimension(getScaledValue(image.getWidth()), getScaledValue(image.getHeight())));
            this.revalidate();
        }
    }
}
